package cn.tedu.system.government.controller;

import cn.tedu.system.base.exception.ServiceException;
import cn.tedu.system.base.response.JsonResult;
import cn.tedu.system.base.response.StatusCode;
import cn.tedu.system.government.pojo.dto.*;

import cn.tedu.system.government.pojo.vo.PoliciesListVO;
import cn.tedu.system.government.pojo.vo.VideoVO;
import cn.tedu.system.government.service.GovernmentService;
import cn.tedu.system.product.pojo.dto.ProductDto;
import cn.tedu.system.product.pojo.dto.ProductIsAParam;
import cn.tedu.system.product.pojo.vo.ProductVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import cn.tedu.system.product.pojo.dto.ProductDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static java.net.URLEncoder.encode;

@Slf4j
@Api(tags = "07.助农宣传模块")
@RestController
@RequestMapping("/api/v1/government/")
public class GovernmentController {
    @Autowired
    private GovernmentService governmentService;



/*
* 增加下载政策附件
* */
    @ApiOperation("下载附件")
    @ApiOperationSupport(order = 91)
@GetMapping("public/download/attachment/{policyId}")
public void downloadAttachment(@PathVariable Long policyId, HttpServletResponse response) {
    String relativePath = governmentService.getAttachmentUrlByPolicyId(policyId);
    if (relativePath == null || relativePath.isEmpty()) {
        throw new ServiceException(StatusCode.FAILED, "附件不存在");
    }

    String basePath = "d:/files";
    File file = new File(basePath + relativePath);

    if (!file.exists()) {
        throw new ServiceException(StatusCode.FAILED, "文件不存在");
    }

    response.setContentType("application/octet-stream");
        String encodedFileName = encode(file.getName(), StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
    } catch (IOException e) {
        throw new ServiceException(StatusCode.FAILED, "文件读取失败");
    }
}






    /*
* 增加助农故事浏览次数
* */
    @ApiOperation("增加助农故事浏览次数")
    @ApiOperationSupport(order = 91)
    @GetMapping("public/increment-video-view-count")
    public JsonResult incrementVideoViewCount(@RequestParam Long videoId) {
        log.debug("增加浏览次数的助农故事ID: {}", videoId);
        governmentService.incrementVideoViewCount(videoId);
        return JsonResult.ok();
    }

    /*
*增加政策浏览次数
*  */
    @ApiOperation("增加政策浏览次数")
    @ApiOperationSupport(order = 90)
    @PostMapping("public/increment-view-count")
    public JsonResult incrementViewCount(@RequestParam Integer policyId) {
        log.debug("增加浏览次数的政策ID: {}", policyId);
        governmentService.incrementPolicyViewCount(policyId);
        return JsonResult.ok();
    }


    @ApiOperation("添加国家政策宣传功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("private/set")
    public JsonResult setPolicies(@RequestBody PoliciesSetDto policiesSetDto) {
        log.debug("宣传政策参数: {}", policiesSetDto);
        governmentService.setPolicies(policiesSetDto);
        return JsonResult.ok();
    }

    @ApiOperation("查询国家政策宣传功能")
    @ApiOperationSupport(order = 20)
    @GetMapping("public/get")
    public JsonResult getPolicies() {
        log.debug("查询国家政策...");
        List<PoliciesListVO> list = governmentService.getList();
        return JsonResult.ok(list);
    }

    @ApiOperation("删除国家政策")
    @ApiOperationSupport(order = 25)
    @PostMapping("private/deletePolicy")
    public JsonResult deletePolicy(Long id) {
        log.debug("删除国家政策参数: {}", id);
        governmentService.deletePolicy(id);
        return JsonResult.ok();
    }

    @ApiOperation("添加助农宣传故事")
    @ApiOperationSupport(order = 30)
    @PostMapping("private/addVideo")
    public JsonResult addVideo(@RequestBody VideoDto videoDto) {
        log.debug("助农宣传故事参数:{}",videoDto);
        governmentService.addVideo(videoDto);
        return JsonResult.ok();
    }

    @ApiOperation("查询助农宣传故事")
    @ApiOperationSupport(order = 40)
    @GetMapping("private/sel")
    public JsonResult getVideos(){
        log.debug("查询助农宣传故事...");
        List<VideoVO> list = governmentService.getVideo();
        return JsonResult.ok(list);
    }
//数据库表改为product,弃用promotion

    @ApiOperation("添加助农宣产品")
    @ApiOperationSupport(order = 50)
    @PostMapping("private/addProduct")
    public JsonResult addProduct(@RequestBody ProductIsAParam productDto) {
        log.debug("助农商品参数: {}", productDto);
        log.debug("Id: {}", productDto.getId());
        log.debug("name: {}", productDto.getName());
        governmentService.addProduct(productDto);
        return JsonResult.ok();
    }

    @ApiOperation("修改助农宣产品")
    @ApiOperationSupport(order = 60)
    @PostMapping("private/reviseProduct")
    public JsonResult reviseProduct(@RequestBody ProductDto productDto){
        log.debug("助农商品修改参数:{}",productDto);
        governmentService.reviseProduct(productDto);
        return JsonResult.ok();
    }

    @ApiOperation("查询助农宣产品")
    @ApiOperationSupport(order = 70)
    @GetMapping("public/list")
    public JsonResult getProductList(Long id, Integer status) {
        log.debug("查询助农商品参数:{},{}",id,status);
        List<ProductVO> list = governmentService.getList(id, status);
        return JsonResult.ok(list);
    }

    @ApiOperation("查询助农宣产品")
    @ApiOperationSupport(order = 75)
    @GetMapping("list")
    public JsonResult getProductList(){
        log.debug("查询所有助农商品...");
        List<ProductVO> list = governmentService.getProductList();
        return JsonResult.ok(list);
    }

    @ApiOperation("根据ID查询助农产品详情")
    @ApiOperationSupport(order = 80)
    @GetMapping("private/product/{id}")
    public JsonResult getProductById(@PathVariable Long id){
        log.debug("查询助农产品详情参数:{}",id);
        ProductVO productVO= governmentService.getProductById(id);
        return JsonResult.ok(productVO);
    }

    @ApiOperation("根据ID查询助农故事")
    @ApiOperationSupport(order = 45)
    @GetMapping("private/sel/{id}")
    public JsonResult getStoryById(@PathVariable Long id) {
        log.debug("查询ID={}的助农故事...", id);
        List<VideoVO> list = governmentService.getStoryById(id);
        return JsonResult.ok(list);
    }

    @ApiOperation("根据ID查询国家政策")
    @ApiOperationSupport(order = 25)
    @GetMapping("public/policy/{id}")
    public JsonResult getPoliciesById(@PathVariable Long id) {
        log.debug("查询ID={}的政策...", id);
        List<PoliciesListVO> list = governmentService.getPoliciesById(id);
        return JsonResult.ok(list);
    }

    //加的接口
//    @PostMapping("private/deletePolicy")
//    public JsonResult deletePolicy(@RequestBody DeletePolicyDTO deletePolicyDTO) {
//        log.debug("删除助农政策: {}", deletePolicyDTO.getPolicyId());
//        governmentService.deletePolicy(deletePolicyDTO.getPolicyId());
//        return JsonResult.ok();
//    }
    @PostMapping("private/deleteProduct")
    public JsonResult deleteProduct(@RequestBody DeleteProductDTO deleteProductDTO) {
        log.debug("删除助农商品: {}", deleteProductDTO.getId());
        Long id = deleteProductDTO.getId();
        if (id == null) {
            log.warn("删除助农商品时，productId为空");
            return JsonResult.error("商品ID不能为空");
        }
        log.debug("删除助农商品: {}", id);
        governmentService.deleteProduct(deleteProductDTO.getId());
        return JsonResult.ok();
    }

    @PostMapping("private/deleteVideo")
    public JsonResult deleteVideo(@RequestBody DeleteVideoDTO deleteVideoDTO) {
        log.debug("删除助农故事: {}", deleteVideoDTO.getVideoId());
        if (deleteVideoDTO.getVideoId() == null) {
            log.warn("删除助农故事时，videoId为空");
            return JsonResult.error("故事ID不能为空");
        }
        governmentService.deleteVideo(deleteVideoDTO.getVideoId());
        return JsonResult.ok();
    }

    @ApiOperation("更新助农政策")
    @PostMapping("private/updatePolicy")
    public JsonResult updatePolicy(@RequestBody PoliciesSetDto policiesSetDto) {
        log.debug("更新助农政策: {}", policiesSetDto);
        governmentService.updatePolicy(policiesSetDto);
        return JsonResult.ok();
    }

    @ApiOperation("更新助农故事")
    @PostMapping("private/updateVideo")
    public JsonResult updateVideo(@RequestBody VideoDto videoDto) {
        log.debug("更新助农故事: {}", videoDto);
        governmentService.updateVideo(videoDto);
        return JsonResult.ok();
    }
//
@ApiOperation("更新助农商品状态")
@ApiOperationSupport(order = 100)
@PostMapping("private/updateProductStatus")
public JsonResult updateProductStatus(@RequestBody UpdateProductStatusDTO dto) {
    log.debug("更新助农商品状态参数: {}", dto);
    governmentService.updateProductStatus(dto.getId(), dto.getStatus());
    return JsonResult.ok();
}

    @ApiOperation("更新助农状态")
    @ApiOperationSupport(order = 90)
    @PostMapping("private/updateAgricultureStatus")
    public JsonResult updateAgricultureStatus(@RequestBody UpdateAgricultureStatusDTO dto) {
        log.debug("更新助农状态参数: {}", dto);
        governmentService.updateAgricultureStatus(dto);
        return JsonResult.ok();
    }
}